package org.dreamwork.cai.io.netty;

import io.netty.buffer.ByteBuf;

public class NettyHelper {
    public static byte[] toBytes (ByteBuf buff) {
        if (buff == null) {
            return null;
        }

        if (buff.hasArray ()) {
            byte[] array = buff.array();
            int offset = buff.arrayOffset() + buff.readerIndex();
            int length = buff.readableBytes();

            if (offset == 0 && length == array.length) {
                return array;
            }

            byte[] data = new byte[length];
            System.arraycopy (array, offset, data, 0, length);
            return data;
        } else {
            int length = buff.readableBytes ();
            byte[] array = new byte[length];
            buff.getBytes(buff.readerIndex(), array);
            return array;
        }
    }
}
